//
//  AuctionCreateOrderVC.swift
//  LeGou
//
//  Created by lxm on 2022/10/17.
//

import UIKit

class AuctionCreateOrderVC: ZMViewController {
    //MARK: --------------------属性--------------------
    var recordId = 0
    
    var orderInfo = ZMUtil.fastNilBehavior(type: OrderInfo.self)
    
    var address = ZMUtil.fastNilBehavior(type: AddressModel.self)
    
    var payHelper = PayHelper()
    //MARK: --------------------UI控件--------------------
    let scrollView = UIScrollView()
    
    let bottomView = UIView()
    
    let confirmButton = ZMUtil.defalutBottomButton(title: "提交订单", font: UIFont.systemFont(ofSize: 14), height: 38)
    
    let scrollContent = ZMUtil.stackView(axis: .vertical, spacing: 16)
    
    let addressView = ZMOrderAddressView().then({$0.layer.cornerRadius=12;$0.layer.masksToBounds=true})
    
    let goodsView = CreateOrderGoodsView().then({$0.layer.cornerRadius=12;$0.layer.masksToBounds=true})
    
    let loading = XMLoadingView()
    
    let payTool = AuctionPayToolView()
    
    let chooseView = AuctionPayType()
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loadInfo()
        loading.showInView(fatherView: view)
        createOrder()
        getwallet()
        getDefaultAddress()
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        title = "确认订单"
        view.addSubview(scrollView)
        scrollView.backgroundColor = "#F5F5F5".zm.hex()
        
        view.addSubview(bottomView)
        
        bottomView.addSubview(confirmButton)
        
        scrollContent.addArrangedSubview(addressView)
        
        scrollView.addSubview(scrollContent)
        
        addressView.address = nil
        
        scrollContent.addArrangedSubview(goodsView)
        
        scrollContent.addArrangedSubview(chooseView)
        
        chooseView.layer.cornerRadius = 12
        
        scrollContent.addArrangedSubview(payTool)
        
        payTool.layer.cornerRadius = 12
        
        payTool.layer.masksToBounds = true
    }
    
    
    func addConstraints() {
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            make.height.equalTo(56)
        }
        
        confirmButton.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.left.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-12)
            make.height.equalTo(38)
        }
        
        scrollView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        scrollContent.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(16)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.centerX.equalToSuperview()
        }
        
        chooseView.snp.makeConstraints { make in
            make.height.equalTo(90)
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        addressView.clickBlock = {[weak self] in
            guard let self = self else {return}
            let vc = ZMAddressListVC()
            vc.chooseAddressBlock = { address in
                guard var temp = self.orderInfo.value else {return}
                self.address.accept(address)
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        address.subscribe(onNext:{ [unowned self] resp in
            self.addressView.address = resp
        }).disposed(by: disposeBag)
        
        confirmButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
             self.onPay()
        }).disposed(by: disposeBag)
        
        // 绑定详情
        orderInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            // 商品信息
            self.goodsView.title.text = "共1件商品"
            self.goodsView.name.text = resp.productName
            self.goodsView.activityNum.setTitle("+\(resp.gainActivity.zm.toString(keep: 4))活跃度", for: .normal)
            self.goodsView.activityNum.sizeToFit()
            self.goodsView.price.text = resp.payPrice.zm.toString(keep: 2)
            self.goodsView.img.zm.setImage(urlStr: resp.image)
            self.goodsView.layoutSubviews()
            self.goodsView.activityNum.isHidden = resp.gainActivity == 0
            self.goodsView.tan.isHidden = resp.gainActivity == 0
            self.chooseView.pointSubLabel.text = "（可获得\(resp.giveIntegral.zm.xmToString(keep: 2))积分）"
            self.payTool.payMoney = resp.payPrice
        }).disposed(by: disposeBag)
        
        // 支付成功
        payHelper.paySuccess = { [weak self] in
            guard let self = self else {return}
            guard let info = self.orderInfo.value
            else {return}
            let gainType = self.chooseView.selectIndex.value
            if gainType == 2 {
                // 合成库
                ZMJumpHelper.destroy(VC: self, classes: [AuctionDetailVC.classForCoder()])
                self.navigationController?.popViewController(animated: true)
            } else {
                let vc = VIPOrderDetail()
                vc.orderNo = info.orderId
                self.navigationController?.pushViewController(vc, animated: true)
                ZMJumpHelper.destroy(VC: self, classes: [AuctionDetailVC.classForCoder(), self.classForCoder])
            }
            ZMNotification.shard.subject.onNext(.auctionRefersh)
        }
        
        chooseView.selectIndex.subscribe(onNext:{ [unowned self] resp in
            let compound = resp == 2
            self.goodsView.tan.isHidden = compound
            self.goodsView.activityNum.isHidden = compound
        }).disposed(by: disposeBag)
    }
    
    func loadInfo() {
//        VIPMallAPI.getPreOrderInfo(orderNo).rxRequest(type: VIPMallModels.PreOrderDetial.self).subscribe(onNext:{ [unowned self] resp in
//            self.loading.hideView(anmation: true)
//            self.orderInfo.accept(resp)
//        }, onError: { e in
//            self.loading.showError(e.localizedDescription)
//        }).disposed(by: disposeBag)
    }
    
    // 支付
    func onPay() {
        guard let info = orderInfo.value else {return}
        guard let ad = address.value else {
            ZMToast.showToast(title: "请选择地址")
            return
        }
        
        guard let type = payTool.selectType.value else {
            ZMToast.showToast(title: "请选择支付方式")
            return
        }
        
        var title = ""
        let gainType = self.chooseView.selectIndex.value
        if gainType == 0 {
            title = "商品?"
        } else if gainType == 1 {
            title = "积分?"
        } else if gainType == 2 {
            title = "加入合成库?"
        }
        
        show(title: "是否确认竞购实际获得".zm.append(str: title, attri: ["c" : Style.mainColor])) {
            self.payHelper.sendPay(currentVC: self, orderNo: info.orderId,
                              payType: type,
                              info: PwdInputInfo(money: info.payPrice.zm.toString(keep: 2), left: "", right: ""),
                              otherInfo: [
                                            "addressId" : ad.id,
                                            "giveType" : gainType
                                        ]) { ok in
                                            
                                        }
        }
    }
    
    func show(title : NSAttributedString, complete : @escaping (()->())) {
        let config = AlertConfig()
        config.attributedTitleStr = title
        config.sureBtnText = "确认"
        config.cancelBtnText = "取消"
        ZMAlertView.alert(config: config) { (index) in
            if index >= 0 {
               complete()
            }
        }
    }
    

    
    func getwallet() {
        Observable.combineLatest(MineAPI.userBanlance.rxRequest(type: [String : Any].self), CommonAPI.paySetting.rxRequest(type: CommonModels.PaySetting.self)).subscribe(onNext:{ [unowned self] resp in
            self.payTool.ckMoney = JSON(resp.0)["mallMoney"].doubleValue
            self.payTool.normalMoney = JSON(resp.0)["money"].doubleValue
            self.payTool.viplabel.text = "创客钱包(¥\( self.payTool.ckMoney.zm.toString(keep: 2)))"
            self.payTool.normalLabel.text = "普通钱包(¥\( self.payTool.normalMoney.zm.toString(keep: 2)))"
            self.payTool.checkState()
            
            self.payTool.wxPayContent.isHidden = resp.1.payWeixinOpen == 0
            self.payTool.aliPayContent.isHidden = resp.1.aliPayStatus == 0
            self.payTool.ckContent.isHidden = resp.1.ckOpenStatus == 0
            self.payTool.balanceContent.isHidden = resp.1.balanceOpenStatus == 0
        }, onError: { e in
        }).disposed(by: disposeBag)
    }
    
    func createOrder() {
        AuctionAPI.createOrder(["recordId" : recordId]).rxRequest(type: OrderInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.orderInfo.accept(resp)
            self.loading.hideView(anmation: true)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    func getDefaultAddress() {
        ZMUtil.listRequest(type: AddressModel.self, api: MineAPI.addressList(["page" : 1,"limit" : 10])) { resp in
            if let data = resp.data, let address = data.first(where: {$0.isDefault}) {
                self.address.accept(address)
            }
        }
    }
    //MARK: --------------------delegate--------------------
}

extension AuctionCreateOrderVC {
    struct OrderInfo : HandyJSON {
        var gainActivity = 0.0
        var giveIntegral = 0.0
        var image = ""
        var orderId = ""
        var payPrice = 0.0
        var productName = ""
    }
}
